package com.smartthinking.cypqro;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.androidquery.AQuery;

import android.graphics.Bitmap;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


@SuppressLint("ValidFragment")
public class ImageFragment extends Fragment {
	private String imageResourceId;
	public Context ctx;
	public ImageView img;
	ProgressBar pbuno;
	//    int total1, position1;
	String position1, total;
	@SuppressLint("ValidFragment")
	LinearLayout ll_pager_control;
	TextView textview1;
//	static Context context;
//	static Bitmap bitmapa;
	Bitmap thumbnail;
	private static ProgressDialog pd = null;
	
	    
	    
	@SuppressLint("ValidFragment")
	//	public ImageFragment(String imageResourceId, Context context, int size, int position) {
	//        this.imageResourceId = imageResourceId;
	//        ctx = context;
	//        total1 = size;
	//        this.position1 = position;
	//    }

	//	public ImageFragment(String position, String imageResourceId, Object object){
	//		
	//		this.imageResourceId = imageResourceId;
	//		total = object;
	//		position1 = position;
	//	}

	public ImageFragment(String position, String imageResourceId, String idr){

		this.imageResourceId = imageResourceId;
		total = idr;
		position1 = position;
	}

	 @Override
	public void onDestroy() {
	        cleanupImageMemory();
	        super.onDestroy();
	    }

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		        
	}



	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		this.ctx= context;
		View view = inflater.inflate(R.layout.image_layout, container, false);
		img = (ImageView) view.findViewById(R.id.imageView1);
		pbuno = (ProgressBar) view.findViewById(R.id.progressBar1);
		
		//        for(int i = 0; i < total; i++){
		//        	Log.i("pager", ""+i);
		//        	if( i == position){
		//        		View circle = new View(ctx);
		//            	circle.setBackgroundResource(R.drawable.circleshape);
		//            	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(21,21);
		//            	params.setMargins(5, 5, 5, 5);
		//            	circle.setLayoutParams(params);
		//            	ll_pager_control.addView(circle);
		//        	}else{
		//        		View circle = new View(ctx);
		//            	circle.setBackgroundResource(R.drawable.circleshapegray);
		//            	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20);
		//            	params.setMargins(5, 5, 5, 5);
		//            	circle.setLayoutParams(params);
		//            	ll_pager_control.addView(circle);
		//        	}
		//        }
		

		new CargarFoto().execute(imageResourceId, position1, total);
//		AQuery aq = new AQuery(getActivity());
//		aq.id(img).image("http://smartthinking.com.mx:9080/CiudadYPoder/contenidos/20130930123433_639.5274811159798_rush.jpg", true, true, 1000, 0);
		return view;
	}

	//    public static Bitmap getBitmapFromURL(String src) {
	//		try {
	//			URL url = new URL(src.replace(" ", "%20"));
	//			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	//			connection.setDoInput(true);
	//			connection.connect();
	//			InputStream input = connection.getInputStream();
	//			Bitmap myBitmap = BitmapFactory.decodeStream(input);
	//			return myBitmap;
	//		} catch (IOException e) {
	//			e.printStackTrace();
	//			return null;
	//		}
	//	}
	
	private void cleanupImageMemory() {
		Log.i("LIMPIO", "cleanupImageMemory"+thumbnail);
        if (thumbnail != null) {
            thumbnail.recycle();
            thumbnail = null;
        }
//        if (img != null) {
//            Drawable d = img.getDrawable();
//            if (d != null && d instanceof BitmapDrawable) {
//                BitmapDrawable db = (BitmapDrawable) d;
//                if (db.getBitmap() != null) {
//                    db.getBitmap().recycle();
//                }
//            }
//            d = null;
//            img = null;
//        }
        System.gc();
        
    }
	
	public void setImageBitmap(Bitmap bm)
    {
		Log.i("LIMPIO", "setImageBitmap"+thumbnail);
        if (thumbnail != null) thumbnail.recycle();
        this.thumbnail = bm;
    }

	public static Bitmap getBitmapFromURL(String src) {
		try {
			Log.e("src",src);
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap bitmap = BitmapFactory.decodeStream(input);
			
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
			out.close();
			out = null;

			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inDither = false; 
			o.inPurgeable = true; 
			o.inInputShareable = true; 
			o.inTempStorage = new byte [64 * 1024]; 
			o.inPreferredConfig = Bitmap.Config. RGB_565;
			
			final int REQUIRED_SIZE=70;
			int scale=1;
			while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
				scale*=2;
			o.inSampleSize = scale;
//			o.inSampleSize = 8;
			BitmapFactory.decodeFile(src, o);
			Log.e("Bitmap","returned");
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			Log.e("Exception",e.getMessage());
//			pd = ProgressDialog.show(context, "Procesando", "Espere...Agregando Usuario", true, false);
			return null;
		}
	}


	//    private Bitmap decodeFile(String params){
	//        try {
	//            //Decode image size
	//            BitmapFactory.Options o = new BitmapFactory.Options();
	//            o.inJustDecodeBounds = true;
	//            BitmapFactory.decodeStream(new FileInputStream(params),null,o);
	//
	//            //The new size we want to scale to
	//            final int REQUIRED_SIZE=70;
	//
	//            //Find the correct scale value. It should be the power of 2.
	//            int scale=1;
	//            while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
	//                scale*=2;
	//
	//            //Decode with inSampleSize
	//            BitmapFactory.Options o2 = new BitmapFactory.Options();
	//            o2.inSampleSize=scale;
	//            return BitmapFactory.decodeStream(new FileInputStream(params));
	//        } catch (FileNotFoundException e) {}
	//        return null;
	//    } 

//	    public void recycleBitmaps() {
//	        if(bitmapa != null) {
//	            bitmapa.recycle();
//	            bitmapa = null;
//	            for(int i = 0; i < bitmapa.length; i++) {
//	                bitmapGlowImages[i].recycle();
//	                bitmapGlowImages[i] = null;
//	            }
//	            System.gc();
//	        }
//	}


//	protected void entryRemoved(boolean evicted, String key,
//            BitmapDrawable oldValue, BitmapDrawable newValue) {
//        if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
//            // The removed entry is a recycling drawable, so notify it 
//            // that it has been removed from the memory cache
//            ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
//        } else {
//            // The removed entry is a standard BitmapDrawable
//
//            if (Utils.hasHoneycomb()) {
//                // We're running on Honeycomb or later, so add the bitmap
//                // to a SoftRefrence set for possible use with inBitmap later
//                mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
//            }
//        }
//    }
	
	public class CargarFoto extends AsyncTask<String, Void, AQuery>{
		int click=0;
		@Override
		protected AQuery doInBackground(String... params) {
//			boolean memCache = false;
//			boolean fileCache = true;
			AQuery aq = new AQuery(getActivity());
			aq.id(img).progress(pbuno).image(params[0], true, true, 300, 0);
//			aq.id(img).progress(pbuno).image(params[0], memCache, fileCache, 400, 0);
//			Bitmap image = getBitmapFromURL(params[0]);
			click = Integer.parseInt(params[2]);
			cleanupImageMemory();
//			setImageBitmap(image);
			Log.i("URLparams", params[0]);
			return aq;
		}

		protected void onPostExecute(AQuery result) {
//			pd.dismiss();
//			pbuno.setVisibility(View.GONE);
//			img.setImageBitmap(result);
			img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i("Peli_idr", ""+click);
					Intent intent = new Intent(getActivity(),Cines.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("peliidr", ""+click);
					startActivity(intent);
				}
			});
			super.onPostExecute(result);
		}


	}
}
